package com.ja.controller;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class ChatWebSocketHandler extends TextWebSocketHandler{
	public static CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<WebSocketSession>();
    /**
     * 接收文本消息，并发送出去
     * js调用websocket.send时候，会调用该方法
     * 
     * 接收消息并处理
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    	//chatTextMessageHandler(message.getPayload());
        //super.handleTextMessage(session, message);
    }
    /**
     * 连接成功以后触发这个方法
     * 可在这里处理离线的信息
     * 
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		Map<String, Object> attributes = session.getAttributes();
		String name = (String) attributes.get("name");
		System.out.println("name  用户建立连接成功"+ name);
		sessions.add(session);
        //处理离线消息
    }
    /**
     * 抛出异常时处理
     * 抛出异常时关闭连接
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        sessions.remove(session);
    }
    
    /**
     * 发送给指定用户
     * @param name  用户名
     * @param data  具体数据
     */
    public void send(String name,String data) {
    	ChatWebSocketHandler c = new ChatWebSocketHandler();
    	TextMessage t = new TextMessage(data);
    	c.sendMessageToUser(name,t);
    }
    /**
     * 当服务器关闭前调用次方法关闭所有websocket 连接以防止从新启动时出现错误
     */
    public void removes() {
    	System.out.println("我进来啦");
    	for (WebSocketSession user : sessions) {
    		try {
				user.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    	}
    	sessions.clear();
    }
    
    
    /**
     * 当用户被强制下线时从websocket里面去掉这个用户
     */
    public static void removeName(String name) {
    	System.out.println("我进来啦删除这个用户啦");
        for (WebSocketSession user : sessions) {
            if (user.getAttributes().get("name").equals(name)) {
            	try {
					user.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            	sessions.remove(user);
            	break;
            }
        }
    }
    
    /**
     * 给某个用户发送消息
     * @param userName会员名
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : sessions) {
            if (user.getAttributes().get("name").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    /**
     *给所有在线用户发送消息
     * @param data  具体数据
     */
    public void sendAll(String data) {
    	ChatWebSocketHandler c = new ChatWebSocketHandler();
    	TextMessage t = new TextMessage(data);
    	c.sendMessageToUsers(t);
    }
    /**
     * 给所有在线用户发送消息
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : sessions) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 关闭连接时触发 
     * 连接关闭后处理
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    	System.out.println(session.getAttributes().get("name")+"断开了连接");
    	sessions.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
